package com.ruoyi.project.WebMoudle.WxShop.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.constant.WxConstant;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QRCodeUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopSuser;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopVo;
import com.ruoyi.project.WebMoudle.ShopSuser.mapper.ShopSuserMapper;
import com.ruoyi.project.WebMoudle.ShopSuser.service.IShopSuserService;
import com.ruoyi.project.WebMoudle.WxShop.domain.QueryShop;
import com.ruoyi.project.WebMoudle.WxShop.domain.ShopApply;
import com.ruoyi.project.WebMoudle.WxShop.domain.ShopEntity;
import com.ruoyi.project.WebMoudle.WxUser.domain.WxUser;
import com.ruoyi.project.WebMoudle.WxUser.service.IWxUserService;
import com.ruoyi.project.WebMoudle.advShow.domain.AdvDistance;
import com.ruoyi.project.WebMoudle.advShow.domain.SearchShop;
import com.ruoyi.project.WxMoudle.Bases.HttpUtil;
import com.ruoyi.project.WxMoudle.Bases.WeixinConfig;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.mapper.UserMapper;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.system.user.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.WebMoudle.WxShop.mapper.WxShopMapper;
import com.ruoyi.project.WebMoudle.WxShop.domain.WxShop;
import com.ruoyi.project.WebMoudle.WxShop.service.IWxShopService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商家店铺Service业务层处理
 *
 * @author ruoyi
 * @date 2020-06-18
 */
@Service
public class WxShopServiceImpl implements IWxShopService {
    @Autowired
    private WxShopMapper wxShopMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IShopSuserService shopSuserService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询商家店铺
     *
     * @param id 商家店铺ID
     * @return 商家店铺
     */
    @Override
    public WxShop selectWxShopById(Long id) {
        return wxShopMapper.selectWxShopById(id);
    }

    /**
     * 查询商家店铺列表
     *
     * @param wxShop 商家店铺
     * @return 商家店铺
     */
    @Override
    public List<WxShop> selectWxShopList(WxShop wxShop) {
        return wxShopMapper.selectWxShopList(wxShop);
    }

    /**
     * 查询待审核和审核失效的商铺
     *
     * @return
     */
    @Override
    public List<WxShop> selectWxShopList02() {
        return wxShopMapper.selectWxShopList02();
    }

    /**
     * 新增商家店铺
     *
     * @param wxShop 商家店铺
     * @return 结果
     */
    @Override
    public int insertWxShop(WxShop wxShop) {
        wxShop.setCreateTime(DateUtils.getNowDate());
        return wxShopMapper.insertWxShop(wxShop);
    }

    /**
     * 修改商家店铺
     *
     * @param wxShop 商家店铺
     * @return 结果
     */
    @Override
    public int updateWxShop(WxShop wxShop) {
        wxShop.setUpdateTime(DateUtils.getNowDate());
        return wxShopMapper.updateWxShop(wxShop);
    }

    /**
     * 允许商家入驻，审核通过
     *
     * @param shopApply
     * @return
     */
    @Override
    @Transactional
    public int applyWxShop(ShopApply shopApply) {
        try {
            User shopUser = new User();
            //校验手机号是否唯一，登录名是否唯一，通过即可创建后台账户
            int count = userMapper.checkLoginNameUnique(shopApply.getLoginName());
            if (count > 0) {//登录名 不唯一
                return 22;
            }
            if (!StringUtils.isNotEmpty(shopApply.getRoleIds())){
                return 44;
            }
            shopUser.setLoginName(shopApply.getLoginName());//登录名

            shopUser.randomSalt();
            //登录密码
            shopUser.setPassword(passwordService.encryptPassword(shopApply.getLoginName(), WxConstant.DEFAULTPASS, shopUser.getSalt()));
            shopUser.setCreateBy(ShiroUtils.getLoginName());   //创建人
            //后台账号昵称
            shopUser.setUserName(shopApply.getShopName());     //昵称
            //部门，角色,职位
            //1.创建部门
            Dept dept = new Dept();
            dept.setDeptName(WxConstant.ADD_NAME+shopApply.getShopCompany());
            dept.setParentId(WxConstant.DEPT_PARENT_ID);
            deptService.insertDept(dept);
            shopUser.setDeptId(dept.getDeptId());        // 自建部门
            shopUser.setRoleIds(shopApply.getRoleIds());        //角色
            shopUser.setPhonenumber(shopApply.getPhonenumber());   //用户手机号
            // 2.新增用户信息
            int rows = userMapper.insertUser(shopUser);

            // 3.新增用户与角色管理
            userService.insertUserRole(shopUser.getUserId(), shopUser.getRoleIds());
            //4.后台商户账号开通成功，修改商铺上线状态，并插入一条shopsUser数据，设定商铺其他参数
            wxShopMapper.toShop(shopApply.getId(), shopApply.getIsValid(), shopApply.getShopCompany());
            ShopSuser shopSuser = new ShopSuser();
            shopSuser.setShopId(shopApply.getId());//店铺id
            shopSuser.setSysUserId(shopUser.getUserId());//后台账户id
            shopSuser.setWxUserId(shopApply.getWxUserId());   //绑定会员id
            WxUser user = wxUserService.selectWxUserById(shopApply.getWxUserId());
            wxUserService.updateWxUser(user);
            shopSuserService.insertShopSuser(shopSuser);

            /*生成商家收款二维码*/
            String requestUrl = WeixinConfig.NOW_URL+"/wxMoudle/store.html?shopId="+shopApply.getId()+ "&type=1";   //请求公众号商铺详情页面
            String logoPath = "";       //图片地址
            String uploadPath = RuoYiConfig.getProfile();                            //下载位置
            String fileName = QRCodeUtils.encode(requestUrl, logoPath, uploadPath, true);
            String pathFileName = Constants.RESOURCE_PREFIX  + "/" + fileName;
            wxShopMapper.updateShopImg(shopApply.getId(),pathFileName);

            /*短信通知对方*/
            StringBuilder sb = new StringBuilder();
            sb.append("accountSid").append("=").append(WeixinConfig.ACCOUNT_SID);
            sb.append("&to").append("=").append(shopApply.getPhonenumber());
            sb.append("&param").append("=").append(shopApply.getLoginName()+","+WxConstant.DEFAULTPASS);
            sb.append("&templateid").append("=").append(WeixinConfig.ADVISE_TEMPLATE);
            String body = sb.toString() + HttpUtil.createCommonParam(WeixinConfig.ACCOUNT_SID, WeixinConfig.AUTH_TOKEN);
            String result = HttpUtil.post(WeixinConfig.BASE_URL, body);
            System.out.println(result);

            return rows;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 删除商家店铺对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteWxShopByIds(String ids) {
        return wxShopMapper.deleteWxShopByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除商家店铺信息
     *
     * @param id 商家店铺ID
     * @return 结果
     */
    @Override
    public int deleteWxShopById(Long id) {
        return wxShopMapper.deleteWxShopById(id);
    }

    //查询该类别下是否存在商铺还\
    @Override
    public List<ShopEntity> selectShopsByType(String id) {
        return wxShopMapper.selectShopsByType(Long.parseLong(id));
    }

    //更新审核状态
    @Override
    public int updateValid(Long id, String isValid) {
        return wxShopMapper.updateValid(id, isValid);
    }

    @Override
    public List<AdvDistance> querySomeShop(QueryShop queryShop) {
        return wxShopMapper.querySomeShop(queryShop);
    }

    @Override
    public List<AdvDistance> queryHotShopList(QueryShop queryShop) {
        return wxShopMapper.queryHotShopList(queryShop);
    }

    /*<!--定时修改让利比-->*/
    @Override
    public int updateDiscountRatio() {
        return wxShopMapper.updateDiscountRatio();
    }


    @Override
    public List<WxShop> searchShopList(SearchShop ssp) {
        return wxShopMapper.searchShopList(ssp);
    }

    @Override
    public List<WxShop> offList(WxShop wxShop) {
        return wxShopMapper.offList(wxShop);
    }

    @Override
    public ShopEntity queryByShopCompany(String shopCompany,String status) {
        return wxShopMapper.queryByShopCompany(shopCompany,status);
    }

    @Override
    public ShopVo selectApplyShop(Long wxUserId) {
        return wxShopMapper.selectApplyShop(wxUserId);
    }

    @Override
    public int updateMoney(Long shopId, BigDecimal belongShop$) {
        return wxShopMapper.updateMoney(shopId,belongShop$);
    }

    @Override
    public String queryShopMoneySum() {
        return wxShopMapper.queryShopMoneySum();
    }

    @Override
    public int updateShopImg(Long id, String pathFileName) {
        return wxShopMapper.updateShopImg(id,pathFileName);
    }

    @Override
    public int queryApplyShopCount() {
        return wxShopMapper.queryApplyShopCount();
    }

    @Override
    public WxShop selecShopMoneyById(Long shopId) {
        return wxShopMapper.selecShopMoneyById(shopId);
    }

    @Override
    public List<WxShop> isShowList(WxShop wxShop) {
        return wxShopMapper.isShowList(wxShop);
    }
}
